<template>
  <base-layout>
    <div class="class-create">
      <a-card title="新增班级" :bordered="false">
        <a-form
          :model="formState"
          :rules="rules"
          ref="formRef"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-form-item label="班级名称" name="className">
            <a-input v-model:value="formState.className" placeholder="请输入班级名称" />
          </a-form-item>
          
          <a-form-item label="年级" name="grade">
            <a-select v-model:value="formState.grade" placeholder="请选择年级">
              <a-select-option value="2024">2024级</a-select-option>
              <a-select-option value="2023">2023级</a-select-option>
              <a-select-option value="2022">2022级</a-select-option>
              <a-select-option value="2021">2021级</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="专业" name="major">
            <a-select v-model:value="formState.major" placeholder="请选择专业">
              <a-select-option value="软件工程">软件工程</a-select-option>
              <a-select-option value="计算机科学与技术">计算机科学与技术</a-select-option>
              <a-select-option value="网络工程">网络工程</a-select-option>
              <a-select-option value="物联网工程">物联网工程</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="学业导师" name="tutor">
            <a-select v-model:value="formState.tutor" placeholder="请选择学业导师">
              <a-select-option value="1">张老师</a-select-option>
              <a-select-option value="2">李老师</a-select-option>
              <a-select-option value="3">王老师</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="备注" name="remark">
            <a-textarea
              v-model:value="formState.remark"
              placeholder="请输入备注信息"
              :rows="4"
            />
          </a-form-item>

          <a-form-item label="导入学生" name="students">
            <div class="upload-area">
              <a-upload
                accept=".xlsx,.xls"
                :before-upload="handleBeforeUpload"
                :show-upload-list="false"
              >
                <a-button type="primary">
                  <template #icon><upload-outlined /></template>
                  选择Excel文件
                </a-button>
              </a-upload>
              <a-button @click="downloadTemplate" type="link">
                <template #icon><download-outlined /></template>
                下载导入模板
              </a-button>
            </div>
            <div v-if="importedStudents.length > 0" class="preview-table">
              <div class="preview-header">
                <span>已导入 {{ importedStudents.length }} 名学生</span>
                <a-button type="link" danger @click="clearImportedStudents">
                  <template #icon><delete-outlined /></template>
                  清空
                </a-button>
              </div>
              <a-table
                :columns="studentColumns"
                :data-source="importedStudents"
                :pagination="false"
                size="small"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'action'">
                    <a-button type="link" danger @click="removeStudent(record)">删除</a-button>
                  </template>
                </template>
              </a-table>
            </div>
          </a-form-item>

          <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
            <a-space>
              <a-button type="primary" @click="handleSubmit">提交</a-button>
              <a-button @click="handleReset">重置</a-button>
              <a-button @click="handleBack">返回</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </base-layout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import { useRouter } from 'vue-router'
import { 
  UploadOutlined, 
  DownloadOutlined, 
  DeleteOutlined 
} from '@ant-design/icons-vue'
import * as XLSX from 'xlsx'
import { createClass } from '@/api/classes'

const router = useRouter()
const formRef = ref()
const formState = reactive({
  name: '',
  grade: undefined,
  major: undefined,
  teacher: undefined,
  remark: ''
})

const rules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { min: 3, max: 50, message: '班级名称长度应在 3-50 个字符之间', trigger: 'blur' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ],
  major: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  tutor: [
    { required: true, message: '请选择学业导师', trigger: 'change' }
  ]
}

const importedStudents = ref([])

const studentColumns = [
  {
    title: '学号',
    dataIndex: 'studentId',
    key: 'studentId',
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '班级',
    dataIndex: 'class',
    key: 'class',
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
  }
]

// 处理文件上传前的验证
const handleBeforeUpload = (file) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase())
  if (!isExcel) {
    message.error('只能上传 Excel 文件！')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('文件大小不能超过 2MB！')
    return false
  }

  // 读取Excel文件
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = XLSX.read(data, { type: 'array' })
      const firstSheetName = workbook.SheetNames[0]
      const worksheet = workbook.Sheets[firstSheetName]
      const results = XLSX.utils.sheet_to_json(worksheet)

      // 验证数据格式
      const validResults = results.filter(item => {
        return item['学号'] && item['姓名'] && item['班级']
      }).map((item, index) => ({
        key: index,
        studentId: item['学号'],
        name: item['姓名'],
        class: item['班级']
      }))

      if (validResults.length === 0) {
        message.error('Excel文件格式不正确或没有数据！')
        return
      }

      importedStudents.value = validResults
      message.success(`成功导入 ${validResults.length} 名学生`)
    } catch (error) {
      console.error('解析Excel文件失败:', error)
      message.error('解析Excel文件失败！')
    }
  }
  reader.readAsArrayBuffer(file)
  return false
}

// 下载导入模板
const downloadTemplate = () => {
  const template = [
    ['学号', '姓名', '班级'],
    ['2024001', '张三', '软件工程2024-1班'],
    ['2024002', '李四', '软件工程2024-1班']
  ]
  
  const ws = XLSX.utils.aoa_to_sheet(template)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '学生名单')
  
  XLSX.writeFile(wb, '学生导入模板.xlsx')
}

// 清空导入的学生
const clearImportedStudents = () => {
  importedStudents.value = []
}

// 删除单个学生
const removeStudent = (record) => {
  importedStudents.value = importedStudents.value.filter(item => item.key !== record.key)
}

// 修改提交方法，加入导入的学生数据
const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const submitData = {
        ...formState,
        students: importedStudents.value
      }
      submitData.studentCount = submitData.students.length
      console.log('提交数据:', submitData)
      message.success('提交成功')
      await createClass(submitData);
      router.push('/class-manage')
    })
    .catch(error => {
      console.log('验证失败:', error)
    })
}

const handleReset = () => {
  formRef.value.resetFields()
}

const handleBack = () => {
  router.push('/class-manage')
}
</script>

<style scoped>
.class-create {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.upload-area {
  display: flex;
  align-items: center;
  gap: 16px;
}

.preview-table {
  margin-top: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 2px;
  padding: 16px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
</style> 